local app = require "app"
local gamelib = require "club.threecard.gamelib"

local Vector2 = CS.UnityEngine.Vector2

local M = gamelib.ui.element()

M.store_watchers = {
    player = {
        ["筹码变更"] = function(self, store, state, args, init)
            if init then
                self:init()
                return
            end

            self:update_chip(args.new, args.old)
        end,

        ["钻石变更"] = function(self, store, state)
            app.utility.digit(self.diamond_txt, nil, state.diamond)
        end,

        ["头像变更"] = function(self, store, state, args, init) 
            self.avatar_icon:set_head(state.head)
        end,

        ["等级变更"] = function(self, store, state)
            self.level_txt.text = tostring(state.level)
        end,
        ["经验变更"] = function(self, store, state)
            self.exp_bar.value = state.exp / state.max_exp
         end,
        ["最大经验变更"] = function(self, store, state)
            self.exp_bar.value = state.exp / state.max_exp
        end
    }

}

local default_res = "club.threecard.gamelib/ui/widgets.b:player_info"
function M:ctor(res)
    self.res = res or default_res

    local AvatarIcon = require "ui.Common.AvatarIcon"
    self.avatar_icon = AvatarIcon.new()
    local Chatter = require "club.threecard.gamelib.widgets.Chatter"
    self.chatter = Chatter.new()
end

function M:get_chip_transform()
    return self.chip_root
end

function M:on_injected(bind)
    bind("gameobject.element", self.head_obj, self.avatar_icon)
    bind("gameobject.element", self.chatter_obj, self.chatter)
end

function M:init()
    local player = app.kbe.player()
    self.name_txt.text = player.name
    self.chip_txt.text = app.i18n.number(player.chip, "chip2")
end

function M:update_chip(current, old)
    if current == old then
        return
    end

    if self.is_silence then
        return
    end
    
    app.utility.digit(self.chip_txt, old, current, app.i18n.styles.chip2)
    --self.chip_txt.text = string.format("$%s", current)
end

function M:be_silence(b)
    self.is_silence = b
    if not b then
        local current = app.store.player.state.chip
        local old = app.store.player.state.old_chip
        self:update_chip(current, old)
    end
end

function M:on_release()
    self:super("on_release")
    self.avatar_icon:release()
    self.chatter:release()
end

return M